import dotenv from 'dotenv';
import path from 'path';

// 根据环境加载不同的.env文件
const envFile = process.env.NODE_ENV === 'production'
  ? '.env.production'
  : process.env.NODE_ENV === 'test'
    ? '.env.test'
    : '.env.development';

dotenv.config({
  path: path.resolve(process.cwd(), envFile)
});

// 配置接口
interface Config {
  env: string;
  server: {
    port: number;
    host: string;
    apiPrefix: string;
  };
  database: {
    host: string;
    port: number;
    username: string;
    password: string;
    database: string;
    dialect: 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql';
  };
  redis: {
    host: string;
    port: number;
    password: string | null;
  };
  jwt: {
    secret: string;
    expiresIn: string;
  };
  elasticsearch: {
    host: string;
    port: number;
  };
  upload: {
    provider: 'local' | 'aliyun';
    local: {
      path: string;
      baseUrl: string;
    };
    aliyun: {
      accessKeyId: string;
      accessKeySecret: string;
      bucket: string;
      region: string;
      baseUrl: string;
    };
  };
}

// 配置对象
export const config: Config = {
  env: process.env.NODE_ENV || 'development',
  server: {
    port: parseInt(process.env.SERVER_PORT || '3000', 10),
    host: process.env.SERVER_HOST || 'localhost',
    apiPrefix: process.env.API_PREFIX || '/api',
  },
  database: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '3306', 10),
    username: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || 'password',
    database: process.env.DB_NAME || 'bloghub',
    dialect: (process.env.DB_DIALECT as any) || 'mysql',
  },
  redis: {
    host: process.env.REDIS_HOST || 'localhost',
    port: parseInt(process.env.REDIS_PORT || '6379', 10),
    password: process.env.REDIS_PASSWORD || null,
  },
  jwt: {
    secret: process.env.JWT_SECRET || 'bloghub-secret-key',
    expiresIn: process.env.JWT_EXPIRES_IN || '7d',
  },
  elasticsearch: {
    host: process.env.ES_HOST || 'localhost',
    port: parseInt(process.env.ES_PORT || '9200', 10),
  },
  upload: {
    provider: (process.env.UPLOAD_PROVIDER as 'local' | 'aliyun') || 'local',
    local: {
      path: process.env.UPLOAD_LOCAL_PATH || 'uploads',
      baseUrl: process.env.UPLOAD_LOCAL_BASE_URL || 'http://localhost:3000/uploads',
    },
    aliyun: {
      accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID || '',
      accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET || '',
      bucket: process.env.ALIYUN_BUCKET || '',
      region: process.env.ALIYUN_REGION || '',
      baseUrl: process.env.ALIYUN_BASE_URL || '',
    },
  },
}; 